package org.jeecg.modules.sxaq.qrcode.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sxaq.ior.service.IRecordInoutService;
import org.jeecg.modules.sxaq.utils.AesUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;

/**
 * @Description: 二维码
 * @Author: DHC
 * @Date:  2020-12-01
 */
@Api(tags="二维码信息相关")
@RestController
@RequestMapping("/sys/qrcode")
@Slf4j
public class QRCodeController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IRecordInoutService recordInoutService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RabbitMqClient rabbitMqClient;

    @Value("${sxaq.factoryCode}")
    private String factoryCode;

    @RequestMapping(value = "/getCodeScanningGunResult", method = RequestMethod.POST)
    @ApiOperation("获取扫码枪返回的数据")
    public Result getCodeScanningGunResult(@RequestBody JSONObject scanResult) throws Exception {

        String encryptStr = scanResult.getString("scanResult");
        String scanName = scanResult.getString("scanName");
        String scanCode = scanResult.getString("scanCode");

        // 根据扫码枪数据解密
        Result result = decryptCodeScanningGunResult(encryptStr);
        JSONObject jsonObject = (JSONObject) result.getResult();
        jsonObject.put("scanName", scanName);
        jsonObject.put("scanCode", scanCode);

        return recordInoutService.entranceAndExit1(jsonObject);
    }

    // 以下方法已废弃
    @RequestMapping(value = "/getCodeScanningGunResultByCloud", method = RequestMethod.POST)
    @ApiOperation("获取扫码枪返回的数据（云端）")
    @ResponseBody
    public String getCodeScanningGunResultByCloud(@RequestParam(name = "name") String scanName, @RequestParam(name = "type", required=false) String scanType, @RequestBody String scanResult) {
        try {
            String encryptStr = "";
            String scanCode = "";
            if (StringUtils.isNotBlank(scanResult)) {
                String[] params = StringUtils.split(scanResult, "&&");
                if (params.length > 0) {
                    String[] encryptStrArr = StringUtils.split(params[0], "=");
                    if (encryptStrArr.length == 2) {
                        encryptStr = encryptStrArr[1];
                    }
                }
                if (params.length > 1) {
                    String[] scanCodeArr = StringUtils.split(params[1], "=");
                    if (scanCodeArr.length == 2) {
                        scanCode = scanCodeArr[1];
                    }
                }
            }

            // 根据扫码枪数据解密
            Result result = decryptCodeScanningGunResult(encryptStr);
            JSONObject jsonObject = (JSONObject) result.getResult();
            jsonObject.put("scanName", scanName);
            jsonObject.put("scanCode", scanCode);
            // 1:进场 2:出厂
            if (scanType != null && scanType.equals("in") && !jsonObject.getString("type").equals("1")) {
                return "code=0001";
            }
            if (scanType != null && scanType.equals("out") && !jsonObject.getString("type").equals("2")) {
                return "code=0001";
            }
            Result ret = recordInoutService.entranceAndExit1(jsonObject);
            if (ret.isSuccess()) {
                log.info("---sxaq----扫码云端：OK");
                return "code=0000";
            }
            log.info("---sxaq----扫码云端：" + ret.getMessage());
            return "code=0001";
        } catch (Exception e) {
            log.info("---sxaq----扫码云端：异常");
            return "code=0001";
        }
    }

    @RequestMapping(value = "/scan", method = RequestMethod.POST)
    @ApiOperation("获取扫码枪返回的数据（云端）")
    @ResponseBody
    public String scan(@RequestParam(name = "name") String scanName, @RequestParam(name = "type", required=false) String scanType, @RequestBody String scanResult) {
        try {
            String encryptStr = "";
            String scanCode = "";
            if (StringUtils.isNotBlank(scanResult)) {
                String[] params = StringUtils.split(scanResult, "&&");
                if (params.length > 0) {
                    String[] encryptStrArr = StringUtils.split(params[0], "=");
                    if (encryptStrArr.length == 2) {
                        encryptStr = encryptStrArr[1];
                    }
                }
                if (params.length > 1) {
                    String[] scanCodeArr = StringUtils.split(params[1], "=");
                    if (scanCodeArr.length == 2) {
                        scanCode = scanCodeArr[1];
                    }
                }
            }

            // 根据扫码枪数据解密
            Result result = decryptCodeScanningGunResult(encryptStr);
            JSONObject jsonObject = (JSONObject) result.getResult();
            jsonObject.put("scanName", scanName);
            jsonObject.put("scanCode", scanCode);
            // 1:进场 2:出厂
            if (scanType != null && scanType.equals("in") && !jsonObject.getString("type").equals("1")) {
                return "code=0001";
            }
            if (scanType != null && scanType.equals("out") && !jsonObject.getString("type").equals("2")) {
                return "code=0001";
            }
            Result ret = recordInoutService.entranceAndExit1(jsonObject);
            if (ret.isSuccess()) {
                log.info("---sxaq----扫码云端：OK");
                return "code=0000";
            }
            log.info("---sxaq----扫码云端：" + ret.getMessage());
            return "code=0001";
        } catch (Exception e) {
            log.info("---sxaq----扫码云端：异常");
            return "code=0001";
        }
    }

    // 解密扫码枪返回数据
    private Result<JSONObject> decryptCodeScanningGunResult(String encryptStr) throws Exception {
        Result<JSONObject> result = new Result();
        result.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
        result.setResult(null);
        result.setSuccess(false);

        if (encryptStr==null || encryptStr.isEmpty()) {
            result.setMessage("信息获取失败");
            return result;
        }

        String aesDecryptString = AesUtil.aesDecrypt(encryptStr,CommonConstant.SXAQ_AES_DECRYPT_KEY);
        if (aesDecryptString==null || aesDecryptString.isEmpty()) {
            result.setMessage("解密失败！");
            return result;
        }

        JSONObject jsonObject = JSONObject.parseObject(aesDecryptString);
        if (jsonObject==null || jsonObject.isEmpty()) {
            result.setMessage("解密失败！");
            return result;
        }
        result.setResult(jsonObject);
        return result;
    }

    @RequestMapping(value = "/qrCodeResult", method = RequestMethod.POST)
    @ApiOperation("app端查询是否扫码成功")
    public Result qrCodeResult(@RequestBody JSONObject jsonObject) {
        Result result = new Result();
        result.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
        result.setResult(null);
        result.setMessage("操作失败");
        result.setSuccess(false);


        String userId = jsonObject.getString("userId");
        if (userId==null || userId.isEmpty()) {
            result.setMessage("用户id不能为空！");
            return result;
        }

        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser==null) {
            result.setMessage("用户不存在！");
            return result;
        }


        // 获取当前用户是进场还是出场
        Integer eventType = sysUser.getEventType();

        if (eventType==null) {
            return result;
        }

//        Integer type = Integer.parseInt(jsonObject.getString("type"));
//        // 如果两个值相等的话 就是校验成功了
//        if (eventType==type) {
//
//            String pwd = (String) redisUtil.get(CommonConstant.SXAQ_SCAN_SUCCESS_PASSWORD+"_"+userId);
//            JSONObject pwdObject = new JSONObject();
//            if (type==1) {
//                pwd = "";
//            }
//            // 出场的时候把密码返回
//            pwdObject.put("password",pwd);
//
//            result.setCode(CommonConstant.SC_OK_200);
//            result.setResult(pwdObject);
//            result.setSuccess(true);
//
//            // 删除设置的标示位 表示已经验证成功了
//            redisUtil.del(CommonConstant.SXAQ_SCAN_SUCCESS+"_"+userId);
//            if (type==2) {
//                // 删除对应密码
//                redisUtil.del(CommonConstant.SXAQ_SCAN_SUCCESS_PASSWORD+"_"+userId);
//            }
//        }

        return result;
    }
}
